<template>
  <div class="app-container">
    <!-- 顶部搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="68px">
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker clearable style="width: 100%;"
                            v-model="queryParams.createTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择创建时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 顶部按钮 -->
    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['xqjh:lhxcgjh:add']"-->
<!--        >新增-->
<!--        </el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          :disabled="!selectedRow || (selectedRow.processStatus !== 1 && selectedRow.processStatus !== 4)"
          v-hasPermi="['xqjh:lhxcgjh:edit']"
        >修改
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['xqjh:lhxcgjh:remove']"-->
<!--        >删除-->
<!--        </el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          size="mini"
          type="primary"
          icon="vxe-icon-file-word"
          :disabled="single"
          @click="handleExports"
        >导出采购计划Excel
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          size="mini"
          type="primary"
          icon="vxe-icon-file-word"
          :disabled="single"
          @click="exportWithLhxcgsq"
        >导出物资采购申请Excel
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          :disabled="!selectedRow || (selectedRow.processStatus !== 1 && selectedRow.processStatus !== 4)"
          @click="handleStartTask"
        >发起申请</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          size="mini"
          type="primary"
          icon="el-icon-delete"
          @click="handleRevokeProcess"
          :disabled="!selectedRow || selectedRow.processStatus !== 2"
        >撤销流程</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table @row-click="clickRow" ref="table" highlight-current-row
              :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
              height="300" class="fixedTableTwo" v-loading="loading" :data="lhxcgjhList"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" type="index" :index="indexMethod"/>
      <el-table-column label="6号线采购计划编号" align="center" prop="lhxcgjhId"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物资采购计划详情" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleXqClick(scope.row)"
          >查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="流程状态" align="center" prop="processStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.process_business_status" :value="scope.row.processStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.processStatus==1 || scope.row.processStatus==4"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.processStatus==1 || scope.row.processStatus==4"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleJinDu(scope.row)"
            v-if="scope.row.processStatus !== 1"
          >查询进度</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改6号线采购计划对话框 -->
    <vxe-modal :title="title" v-model="open" width="95%" showFooter show-zoom resize>
      <el-form ref="formDialog" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="创建时间" prop="createTime">
          <el-input disabled v-model="form.createTime" placeholder="自动生成"/>
        </el-form-item>
        <el-card class="box-card">
          <div slot="header" class="clearfix" style="text-align: center;">
            <span style="font-size: 20px; color: #1890ff">6号线采购计划明细信息</span>
          </div>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddLhxcgjhMx">添加</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteLhxcgjhMx">删除</el-button>
            </el-col>
          </el-row>
          <el-table :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                    :data="lhxcgjhMxList" :row-class-name="rowLhxcgjhMxIndex" height="50vh"
                    @selection-change="handleLhxcgjhMxSelectionChange" ref="lhxcgjhMx">
            <el-table-column type="selection" width="50" align="center"/>
            <el-table-column label="序号" align="center" prop="index" width="50"/>
            <el-table-column align="center" label="物资名称" prop="wzMc">
              <template slot-scope="scope">
                <el-input disabled v-model="scope.row.wzMc" placeholder="请输入物资名称"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="规格及型号" prop="ggJXh">
              <template slot-scope="scope">
                <el-input disabled v-model="scope.row.ggJXh" placeholder="请输入规格及型号"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="技术、工艺要求等" prop="jsGyYq">
              <template slot-scope="scope">
                <el-input disabled v-model="scope.row.jsGyYq" placeholder="请输入技术、工艺要求等"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="单位" prop="dw">
              <template slot-scope="scope">
                <el-input disabled v-model="scope.row.dw" placeholder="请输入单位"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="数量" prop="sl">
              <template slot-scope="scope">
                <el-input-number disabled style="width: 100%;" v-model="scope.row.sl" placeholder="请输入数量"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="预算单价(元)" prop="ysDj">
              <template slot-scope="scope">
                <el-input-number style="width: 100%;" v-model="scope.row.ysDj" placeholder=""
                                 @change="calculateYsFj(scope.row)"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="预算复价" prop="ysFj">
              <template slot-scope="scope">
                <el-input-number style="width: 100%;" v-model="scope.row.ysFj" placeholder=""/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="购置原因" prop="gzYy">
              <template slot-scope="scope">
                <el-input v-model="scope.row.gzYy" placeholder="请输入购置原因"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="此类设备在本单位拥有及使用情况" prop="yyJSyQk">
              <template slot-scope="scope">
                <el-input v-model="scope.row.yyJSyQk" placeholder="请输入此类设备在本单位拥有及使用情况"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="使用时间" prop="sySj">
              <template slot-scope="scope">
                <el-date-picker disabled clearable v-model="scope.row.sySj" type="date" value-format="yyyy-MM-dd"
                                placeholder="请选择使用时间"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="用途说明" prop="ytSm">
              <template slot-scope="scope">
                <el-input disabled v-model="scope.row.ytSm" placeholder="请输入用途说明"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="备注" prop="bz">
              <template slot-scope="scope">
                <el-input disabled v-model="scope.row.bz" placeholder="请输入备注"/>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer  dialog-footer-center">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 6号线采购计划详情 -->
    <LhxCgJhXq ref="lhxCgJhXq"/>

    <!-- 查询进度 -->
    <Jindu ref="progress"/>
  </div>
</template>

<script>
import {listLhxcgjh, getLhxcgjh, delLhxcgjh, addLhxcgjh, updateLhxcgjh} from "@/api/xqjh/lhxcgjh";
import {getToken} from "@/utils/auth";
import LhxCgJhXq from "@/views/xqjh/lhxcgjh/components/LhxCgJhXq.vue";
import Jindu from "@/views/components/liuChengState/jindu.vue";
import {revokeProcess, startTask} from "@/api/activiti/task";

export default {
  name: "Lhxcgjh",
  dicts: ['process_business_status'],
  components: {Jindu, LhxCgJhXq},
  data() {
    return {
      selectedRow: null, // 保存当前选中的行
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedLhxcgjhMx: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 6号线采购计划表格数据
      lhxcgjhList: [],
      // 6号线采购计划明细表格数据
      lhxcgjhMxList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        createTime: null,
        userId: null,
        deptId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //发起任务
    handleStartTask() {
      const row = this.selectedRow; // 获取当前选中的行
      if (!row) {
        this.$message.error("请先选择一行数据");
        return;
      }
      this.$confirm("是否确认发起申请？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$modal.loading("正在发起申请，请稍后...");
          startTask({ businessKey: row.lhxcgjhId, businessType: 16 }).then(res => {
            this.getList();
            this.$modal.msgSuccess("发起成功");
            this.selectedRow = null
            // 关闭遮罩层
            this.$modal.closeLoading();
          });
        })
        .catch(() => {});
    },
    //撤销流程
    handleRevokeProcess() {
      const row = this.selectedRow; // 获取当前选中的行
      if (!row) {
        this.$message.error("请先选择一行数据");
        return;
      }
      this.$confirm("是否确撤销申请？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$modal.loading("正在撤销申请，请稍后...");
          let params = {
            businessKey: row.lhxcgjhId,
            businessType: 16,
            processInstanceId: row.processInstanceId
          };
          revokeProcess(params).then(res => {
            this.getList();
            this.$modal.msgSuccess("撤销成功");
            this.selectedRow = null
            // 关闭遮罩层
            this.$modal.closeLoading();
          });
        })
        .catch(() => {});
    },
    //查询进度
    handleJinDu(row) {
      this.$refs.progress.handleOpen(row);
    },
    //打开详情
    handleXqClick(row) {
      this.$refs.lhxCgJhXq.handleOpen(row)
    },
    calculateYsFj(row) {
      const sl = parseFloat(row.sl) || 0;
      const ysDj = parseFloat(row.ysDj) || 0;
      row.ysFj = parseFloat((sl * ysDj).toFixed(4)); // 保留 4 位小数
    },
    //点击行 获取行
    clickRow(row) {
      this.selectedRow = row; // 更新选中的行
      const table = this.$refs.table;
      const selectedRows = table.selection;

      // 否则取消之前选中的行，并选中当前点击的行
      selectedRows.forEach(selectedRow => {
        table.toggleRowSelection(selectedRow);
      });
      table.toggleRowSelection(row);
    },
    /** 自定义序号 */
    indexMethod(index) {
      let pageNum = this.queryParams.pageNum - 1;
      if ((pageNum !== -1 && pageNum !== 0)) {
        return (index + 1) + (pageNum * this.queryParams.pageSize);
      } else {
        return (index + 1)
      }
    },
    /** 查询6号线采购计划列表 */
    getList() {
      this.loading = true;
      listLhxcgjh(this.queryParams).then(response => {
        this.lhxcgjhList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        lhxcgjhId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        userId: null,
        deptId: null
      };
      this.lhxcgjhMxList = [];
      this.resetForm("formDialog");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lhxcgjhId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加6号线采购计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const lhxcgjhId = row.lhxcgjhId || this.ids
      getLhxcgjh(lhxcgjhId).then(response => {
        this.form = response.data;
        this.lhxcgjhMxList = response.data.lhxcgjhMxList;
        this.open = true;
        this.title = "修改6号线采购计划";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formDialog"].validate(valid => {
        if (valid) {
          this.form.lhxcgjhMxList = this.lhxcgjhMxList;
          if (this.form.lhxcgjhId != null) {
            updateLhxcgjh(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLhxcgjh(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const lhxcgjhIds = row.lhxcgjhId || this.ids;
      this.$modal.confirm('确定删除选中记录？').then(function () {
        return delLhxcgjh(lhxcgjhIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 6号线采购计划明细序号 */
    rowLhxcgjhMxIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 6号线采购计划明细添加按钮操作 */
    handleAddLhxcgjhMx() {
      let obj = {};
      obj.wzMc = "";
      obj.ggJXh = "";
      obj.jsGyYq = "";
      obj.dw = "";
      obj.sl = "";
      obj.ysDj = "";
      obj.ysFj = "";
      obj.gzYy = "";
      obj.yyJSyQk = "";
      obj.sySj = "";
      obj.ytSm = "";
      obj.bz = "";
      this.lhxcgjhMxList.push(obj);
    },
    /** 6号线采购计划明细删除按钮操作 */
    handleDeleteLhxcgjhMx() {
      if (this.checkedLhxcgjhMx.length == 0) {
        this.$modal.msgError("请先选择要删除的6号线采购计划明细数据");
      } else {
        const lhxcgjhMxList = this.lhxcgjhMxList;
        const checkedLhxcgjhMx = this.checkedLhxcgjhMx;
        this.lhxcgjhMxList = lhxcgjhMxList.filter(function (item) {
          return checkedLhxcgjhMx.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleLhxcgjhMxSelectionChange(selection) {
      this.checkedLhxcgjhMx = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExports() {
      const row = this.selectedRow; // 获取当前选中的行
      this.$modal.confirm('确认导出该采购计划吗?').then(() => {
        this.download('xqjh/lhxcgjh/exportWithTemplates', {
          ...this.selectedRow
        }, `6号线采购计划_${new Date().getTime()}.xlsx`)
      })
    },
    /** 导出物资采购申请Excel */
    exportWithLhxcgsq() {
      const row = this.selectedRow; // 获取当前选中的行
      this.$modal.confirm('确认导出该物资采购申请吗?').then(() => {
        this.download('xqjh/lhxcgjh/exportWithLhxcgsq', {
          ...this.selectedRow
        }, `6号线物资采购申请_${new Date().getTime()}.xlsx`)
      })
    },
  }
};
</script>
